package com.fyt.reachgo.synctask;

import com.fyt.reachgo.domain.TravelGuide;
import com.fyt.reachgo.mapper.TravelGuideMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class LikeCountSyncTask {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private TravelGuideMapper travelGuideMapper;

    @Scheduled(fixedRate = 60000)
    public void syncLikeCount() {
        log.info("开始同步点赞数到数据库...");

        Set<String> keys = redisTemplate.keys("like:*:count");
        if (keys == null || keys.isEmpty()) {
            log.info("没有需要同步的点赞数据");
            return;
        }

        List<TravelGuide> updates = new ArrayList<>();
        for (String key : keys) {
            try {
                String[] parts = key.split(":");
                Integer guideId = Integer.parseInt(parts[1]);
                String countStr = (String) redisTemplate.opsForValue().get(key);

                if (countStr != null) {
                    TravelGuide guide = new TravelGuide();
                    guide.setId(guideId);
                    guide.setLikes(Integer.parseInt(countStr));
                    updates.add(guide);
                }
            } catch (Exception e) {
                log.error("处理Key {} 出错: {}", key, e.getMessage());
            }
        }

        if (!updates.isEmpty()) {
            int affected = travelGuideMapper.batchUpdateLikes(updates);
            log.info("成功同步{}个路书的点赞数", affected);
        }
    }
}
